package cn.laixueit.service.impl;

import cn.laixueit.mapper.CartMapper;
import cn.laixueit.mapper.GoodsMapper;
import cn.laixueit.pojo.Cart;
import cn.laixueit.pojo.CartExample;
import cn.laixueit.pojo.Goods;
import cn.laixueit.pojo.User;
import cn.laixueit.service.CartService;
import cn.laixueit.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private UserService userService;

    @Override
    public void addCart(Long id,Integer uid) {
        Goods goods = goodsMapper.selectByPrimaryKey(id);
        if(goods!=null){
            Cart cart = new Cart();
            cart.setName(goods.getName());
            cart.setNum(1);
            cart.setPrice(goods.getPrice());
            cart.setTotalprice(goods.getPrice());
            List list = JSON.parseObject(goods.getImgs(), List.class);
            Map<String,String> map = JSON.parseObject(list.get(0).toString(), Map.class);
            String url = map.get("url");
            cart.setImg(url);
            cart.setUid(uid);
            cartMapper.insertSelective(cart);
        }else{
            throw  new RuntimeException("商品已下架，请刷新页面或重试");
        }
    }

    @Override
    public List<Cart> cartList(String username) {

        User user  = userService.findUserByUsername(username);
        if(user!=null) {
            Cart cart = new Cart();
            cart.setUid(user.getId());
            CartExample example = getCartExample(cart);
            List<Cart> cartList = cartMapper.selectByExample(example);
            return cartList;
        }
        throw  new RuntimeException("非法操作，该用户不存在");
    }

    @Override
    public void changeNum(Integer num, Integer id) {
        Cart cart = cartMapper.selectByPrimaryKey(id);
        Integer sum = cart.getNum()+num;
        if(sum<1){
            cartMapper.deleteByPrimaryKey(id);
        }else{
            cart.setNum(sum);
            cartMapper.updateByPrimaryKeySelective(cart);
        }
    }

    private CartExample getCartExample(Cart cart){
        CartExample example = new CartExample();
        if(cart!=null){
            CartExample.Criteria criteria = example.createCriteria();
            if(cart.getUid()!=null){
                criteria.andUidEqualTo(cart.getUid());
            }
        }
        return  example;
    }
}
